﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using Bzure.Security.Permissions;
using Bzure.Common.Core;
using Bzure.Common.Transactions;

namespace Bzure.Apps.Security.DataAccess
{
    [Export(typeof(IContractFactory<IRoleContract>))]
    public class RoleContractBuilder : IContractFactory<IRoleContract>
    {
        /// <summary>
        /// 契约实现的版本号
        /// </summary>
        public float ContractVersion { get { return 1.0F; } }
        public IRoleContract Build()
        {
            return new RoleContractProvider();
        }
    }
    public class RoleContractProvider : TransactionSupportBase, IRoleContract
    {
        /// <summary>
        /// 创建而不打开连接
        /// </summary>
        /// <returns></returns>
        public override System.Data.Common.DbConnection CreateConnection()
        {
            return ConnectionFactory.GetConnection();
        }
        public TeamRole[] GetAllTeamRoles()
        {
            return new RoleRepository(this).GetAllRoles();
        }
        public TreeRole[] GetAllTreeRoles()
        {
            return default(TreeRole[]);
        }
        public IDroit[] GetDroitsByRole(ISecurityRole role)
        {
            List<Droit> droits = new List<Droit>();
             DroitResource [] drs= new DroitResourceRepository(this).GetDroitsByRole(role);
             if (drs.IsNotNullAndEmpty())
             {
                 foreach (DroitResource resource in drs)
                 {
                     droits.Add(ConvertToDroit(resource));
                 }
             }
             return droits.ToArray();
          
        }
        Droit ConvertToDroit(DroitResource resource)
        {
            Droit droit = new Droit(resource.ResourceName);
            foreach (int right in resource.RightValue.ToFlags())
            {
                droit.AddAccessCode(new AccessCode(right));
            }
            return droit;
        }
        public string[] GetTeamRoleIDsByUserID(string UserID)
        {
            return new UserRoleMapRepository(this).GetTeamRoleIDsByUser(UserID);
        }
    }
}
